package design_modle.factory;

import design_modle.Strategy.CashContext;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        // 创建主窗口
        JFrame frame = new JFrame("商场收银系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);
        frame.setLayout(new GridLayout(4, 2));

        // 创建组件
        JLabel typeLabel = new JLabel("选择收费类型:");
        JComboBox<String> typeComboBox = new JComboBox<>(new String[]{
                "正常收费", "满300返100", "打8折"
        });

        JLabel amountLabel = new JLabel("输入金额:");
        JTextField amountField = new JTextField();

        JButton calculateButton = new JButton("计算价格");
        JLabel resultLabel = new JLabel("结果: ");

        // 布局管理
        frame.add(typeLabel);
        frame.add(typeComboBox);
        frame.add(amountLabel);
        frame.add(amountField);
        frame.add(calculateButton);
        frame.add(resultLabel);

        // 添加事件监听
        calculateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String selectedType = (String) typeComboBox.getSelectedItem();
                    double amount = Double.parseDouble(amountField.getText());

                    // 使用工厂创建计费策略
//                    CashSuper cashSuper = CashFactory.createCashAdapter(selectedType);
//                    double totalPrice = cashSuper.acceptCash(amount);

//                    CashContext cc = switch (selectedType){
//                        case "正常收费" -> new CashContext(new CashNomal()) ;
//                        case "满300返100" -> new CashContext(new CashReturn(300 , 100));
//                        case "打8折" ->new CashContext(new CahRebate(0.8)) ;
//                        default -> throw new IllegalStateException("Unexpected value: " + selectedType);
//                    };

                    double totalPrice = new CashContext(selectedType).getResult(amount);

                    resultLabel.setText(String.format("应付金额: %.2f 元", totalPrice));

                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(frame,
                            "请输入有效的数字金额",
                            "输入错误", JOptionPane.ERROR_MESSAGE);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame,
                            "发生未知错误: " + ex.getMessage(),
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 显示窗口
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}